package com.smshen.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

/**
 * @program: ParsePDM-master
 * @description: 读取文件工具
 * @author: liangxiaochen
 * @create: 2019-11-22 10:42
 **/
public class FileUtil {

    private FileUtil() {
    }

    /**
     * 最大文件300MB
     **/
    private static final long MAX_FILE_SIZE = 1024 * 1024 * 300;

    /**
     * 读取文件，并返回文件字符串，如果文件过大，则返回空字符串
     *
     * @param filePath
     * @author liangxiaochen
     * @createDate 2019/11/22 10:44
     **/
    public static String readFileToString(String filePath) {

        File file = new File(filePath);

        boolean fileExists = file.exists();
        boolean isFile = file.isFile();
        if (!fileExists || !isFile) {
            return null;
        }

        Long fileSize = file.length();
        if (MAX_FILE_SIZE < fileSize) {
            return "";
        }
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[fileSize.intValue()];
            fileInputStream.read(buffer);
            String fileStr = new String(buffer);
            return fileStr.replaceAll("[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]", "");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
